package xyz.shenmegui.foodcheckserver.service.impl;

import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;
import xyz.shenmegui.foodcheckserver.DO.Compound;
import xyz.shenmegui.foodcheckserver.DO.Record;
import xyz.shenmegui.foodcheckserver.VO.RecordDetail;
import xyz.shenmegui.foodcheckserver.mapper.RecordMapper;
import xyz.shenmegui.foodcheckserver.service.CompoundService;
import xyz.shenmegui.foodcheckserver.service.RecordService;

import java.util.ArrayList;
import java.util.List;

@Service
@Transactional
public class RecordServiceImpl implements RecordService {

    @Autowired
    private RecordMapper recordMapper;

    @Autowired
    private CompoundService compoundService;

    @Override
    public List<RecordDetail> selectByUserId(int uid) {
        List<Record> records = recordMapper.selectList(new QueryWrapper<Record>().eq("uid", uid).eq("deleted", 0).orderByDesc("create_time"));
        List<RecordDetail> recordDetails = new ArrayList<>();
        for (Record r: records) {
            List<Compound> compounds = compoundService.selectByIds(r.getCid());
            recordDetails.add(new RecordDetail(r, compounds));
        }
        return recordDetails;
    }

    @Override
    public List<RecordDetail> selectByCollected(int uid) {
        List<Record> records = recordMapper.selectList(new QueryWrapper<Record>().eq("uid", uid).eq("flag", 1).eq("deleted", 0).orderByDesc("update_time"));
        List<RecordDetail> recordDetails = new ArrayList<>();
        for (Record r: records) {
            List<Compound> compounds = compoundService.selectByIds(r.getCid());
            recordDetails.add(new RecordDetail(r, compounds));
        }
        return recordDetails;
    }

    @Override
    public Record selectById(int id) {
        return recordMapper.selectById(id);
    }

    @Override
    public int deleteByIdLogic(Record record) {
        if (record.getDeleted() == 1) {
            return 0;
        }
        record.setDeleted(1);
        return recordMapper.updateById(record);
    }

    @Override
    public int deleteByIdPhysically(Record record) {
        return recordMapper.deleteById(record);
    }

    @Override
    public int deleteByIdCollection(Record record) {
        if (record.getFlag() == 0) {
            return 0;
        }
        record.setFlag(0);
        return recordMapper.updateById(record);
    }

    @Override
    public int insert(Record record) {
        return recordMapper.insert(record);
    }

    @Override
    public int addCollection(Record record) {
        record.setFlag(1);
        return recordMapper.updateById(record);
    }

    @Override
    public int update(Record record) {
        return recordMapper.updateById(record);
    }
}
